import React, { useState, useEffect, useCallback, useRef } from 'react';
import type { ProColumns, ProTableProps } from '@ant-design/pro-table';
import { ProTable, MyProTableProps } from '@/components/KaiyaTable/index';
import { Modal, Tree, Select, Input, Button, DatePicker, message } from 'antd';
import { FilterOutlined, PlusOutlined } from '@ant-design/icons';
import request from 'umi-request';
import { history } from 'umi';
import moment from 'moment';

import {
  getRoleList,
  getOrgTree,
  deleteRoleById,
  updateRoleStatus,
} from '@/services/userControl';
import { getStatusMap } from '@/services/common';

import { orgGetOne } from '@/services/common';

const UserManage: React.FC = () => {
  const tableRef = useRef<any>();
  const [selectedRowKeys, setselectedRowKeys] = useState([]);

  const [departmentList, setDepartmentList] = useState({});

  const [roleStatusMap, setroleStatusMap] = useState({});
  const TableCustomDeploy = {
    componentName: 'customTable',
  };
  useEffect(() => {
    getDepartmentTreeByRole();
    getStatus();
  }, []);
  const getRoleData = async (params) => {
    let res = await getRoleList(params);
    let lastData = {
      ...res,
      page: res.currentPage,
      total: res.totalRecords,
      success: true,
    };
    return Promise.resolve(lastData);
  };

  const formatTreeData = (data: any) => {
    if (Array.isArray(data) && data.length > 0) {
      data.forEach((ele) => {
        ele.title = ele.name;
        ele.key = ele.id;
        if (ele.children && ele.children.length > 0) {
          formatTreeData(ele.children);
        }
      });
    }
    return data;
  };
  const getStatus = async () => {
    const res = await getStatusMap('sys_common_status');
    console.log(res);
    let obj = {};
    for (const item of res?.data) {
      obj[item.dictValue] = { text: item.dictLabel };
    }
    setroleStatusMap(obj);
  };

  const getDepartmentTreeByRole = async () => {
    // 根据接口获取值
    const res = await orgGetOne({ isScope: 1 });
    let obj = {};
    for (const item of res?.data) {
      obj[item.id] = { text: item.name };
    }
    setDepartmentList(obj);
  };
  const updateRoleStatusPost = async (arrId: number[], status: '1' | '2') => {
    console.log(arrId, status);

    Modal.warning({
      title: `${status === '1' ? '启用' : '停用'}提示信息`,
      content: `${
        status === '1'
          ? '确认启用所选用户？'
          : '停用角色后，该角色将无法使用，请确认是否停用！'
      }`,
      closable: true,
      okText: '确认',
      onOk: async () => {
        const res = await updateRoleStatus({ arrId, status });
        if (res.code === 200) {
          message.success(`${status === '1' ? '启用' : '停用'}成功`);
          tableRef.current.reloadAndRest();
        } else {
          message.error(res.message);
        }
      },
    });
  };
  const getTableBasicDeploy = (): ProTableProps<any, any, any> => {
    const columns: ProColumns[] = [
      {
        dataIndex: 'index',
        title: '序号',
        valueType: 'indexBorder',
      },
      {
        title: '角色名',
        dataIndex: 'name',
        valueType: 'text',
        order: 4,
      },
      {
        title: '角色描述',
        dataIndex: 'description',
        valueType: 'text',
        hideInSearch: true,
      },
      {
        title: '创建者',
        dataIndex: 'createdBy',
        valueType: 'text',
        hideInSearch: true,
      },
      {
        title: '创建日期',
        dataIndex: 'createdTime',
        valueType: 'dateRange',
        order: 3,
        // renderFormItem: (_, { defaultRender }) => {
        //   return <DatePicker.RangePicker />;
        // },
        render: (text, record, _, action) => {
          let data = record.createdTime;
          return <span>{moment(data).format('YYYY-MM-DD')}</span>;
        },
      },
      {
        title: '归属机构',
        dataIndex: 'organizationName',
        order: 1,
        valueEnum: departmentList,
      },
      {
        title: '状态',
        dataIndex: 'status',
        valueType: 'select',
        order: 2,
        valueEnum: roleStatusMap,
      },
      {
        title: '操作',
        valueType: 'option',
        render: (text, record, _, action) => [
          <a
            href={record.url}
            target="_blank"
            rel="noopener noreferrer"
            key="view"
            onClick={() => {
              history.push({
                pathname: '/features/userPermission/role/add',
                state: {
                  pageType: 'details',
                  roleId: record.id,
                },
              });
            }}
          >
            详情
          </a>,
          <a
            href={record.url}
            target="_blank"
            rel="noopener noreferrer"
            key="view"
            onClick={() => {
              history.push({
                pathname: '/features/userPermission/role/add',
                state: {
                  pageType: 'edit',
                  roleId: record.id,
                },
              });
            }}
          >
            编辑
          </a>,
          <a
            href={record.url}
            target="_blank"
            rel="noopener noreferrer"
            key="view"
            onClick={() => {
              console.log(record);
              history.push({
                pathname: '/features/userPermission/role/authorization',
                state: {
                  roleId: record.id,
                  name: record.name,
                  description: record.description,
                },
              });
            }}
          >
            授权
          </a>,
          <a
            href={record.url}
            target="_blank"
            rel="noopener noreferrer"
            key="view"
            onClick={async () => {
              Modal.warning({
                title: '删除提示信息',
                content: '删除用户后，该用户将无法登录，且无法恢复！',
                closable: true,
                okText: '确认',
                onOk: async () => {
                  const id = record.id;
                  const res = await deleteRoleById(id);
                  console.log(res);
                  if (res.code === 200) {
                    tableRef.current.reloadAndRest();
                  }
                },
              });
            }}
          >
            删除
          </a>,
          <a
            href={record.url}
            target="_blank"
            rel="noopener noreferrer"
            key="view"
            onClick={() => {
              const ids = record.id;
              updateRoleStatusPost([ids], '2');
            }}
          >
            停用
          </a>,
        ],
      },
    ];
    const rowSelection = {
      onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
        setselectedRowKeys(selectedRowKeys);
        // console.log(
        //   `selectedRowKeys: ${selectedRowKeys}`,
        //   'selectedRows: ',
        //   selectedRows,
        // );
      },
      getCheckboxProps: (record: any) => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    };
    return {
      actionRef: tableRef,
      columns,
      request: async (params = {}, sort, filter) => {
        console.log('request请求发出', params, filter);
        let dateObj = params.createdTime
          ? {
              createTimestampStart:
                new Date(params.createdTime[0]).getTime() / 1000,
              createTimestampEnd:
                new Date(params.createdTime[1]).getTime() / 1000,
            }
          : {};

        let lastParams = {
          ...params,
          ...dateObj,
          // roleOrgId: checkedKeys,
          pageNumber: params.current,
          pageSize: params.pageSize,
        };
        if (lastParams.name === '') {
          delete lastParams.name;
        }
        delete lastParams.current;
        delete lastParams.createdTime;
        console.log(lastParams);
        return getRoleData(lastParams);
      },
      rowSelection: {
        type: 'checkbox',
        ...rowSelection,
      },
      pagination: {
        pageSize: 5,
      },
      rowKey: 'id',
      toolBarRender: () => [
        <Button
          icon={<PlusOutlined />}
          onClick={() => {
            history.push({
              pathname: '/features/userPermission/role/add',
              state: {
                pageType: 'add',
              },
            });
          }}
        >
          新增角色
        </Button>,
        <Button
          onClick={() => {
            updateRoleStatusPost(selectedRowKeys, '2');
          }}
        >
          停用
        </Button>,
        <Button
          onClick={() => {
            updateRoleStatusPost(selectedRowKeys, '1');
          }}
        >
          启用
        </Button>,
      ],
    };
  };
  const jsonOption: MyProTableProps = {
    TableCustomDeploy,
    TableBasicDeploy: getTableBasicDeploy,
  };
  return (
    <div>
      <ProTable {...jsonOption}></ProTable>
    </div>
  );
};
const mapStateToProps = (state: any) => {
  return {
    roleStatusMap: state.common.status,
  };
};

export default UserManage;
